package com.ys.controller.api.outer;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.api.internal.util.StringUtils;
import com.ys.config.MyConfig;
import com.ys.entity.base.TbUserAttendance;
import com.ys.entity.base.TbUserJobLevelManage;
import com.ys.mapper.hr.HrMapper;
import com.ys.service.base.TbUserAttendanceService;
import com.ys.util.DateUtil;
import com.ys.util.RedisUtil;
import com.ys.vo.R;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/api/outer/dingDingApi")
public class ApiOutDingDingController {
    private static final Logger logger = LoggerFactory.getLogger(ApiOutDingDingController.class);

    //钉钉企业ID
    private static String CORPID = MyConfig.getDingCorpid();
    //钉钉H5应用ID：AGENTID
    private static String AGENTID = MyConfig.getDingAgentid();
    //钉钉H5应用KEY
    private static String H5APPKEY = MyConfig.getDingAppkey();
    //钉钉H5应用secret
    private static String H5APPSECERT = MyConfig.getDingAppsecret();
    //钉钉H5应用默认的机器人唯一标识
    private static String DINGROBOTAPPKEY = MyConfig.getDingRobotAppKey();

    //一天上班7.5小时
    private BigDecimal oneDayWorkHour = new BigDecimal(7.5);

    //redis工具类
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HrMapper hrMapper;

    @Autowired
    private TbUserAttendanceService tbUserAttendanceService;

    /**
     * 获取企业内部应用的accessToken api 新版
     * @return 返回accessToken
     * @throws Exception
     */
    public String getAccessToken() throws Exception {
        //先查缓存
        String accessToken = null ;
        if(redisUtil.get("DingDingAccessToken"+AGENTID)!= null && !"".equals(redisUtil.get("DingDingAccessToken"+AGENTID))){
            accessToken = redisUtil.get("DingDingAccessToken"+AGENTID) ;
        }else {
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
            config.protocol = "https";
            config.regionId = "central";
            com.aliyun.dingtalkoauth2_1_0.Client client = new com.aliyun.dingtalkoauth2_1_0.Client(config);
            com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                    .setAppKey(H5APPKEY)
                    .setAppSecret(H5APPSECERT);
            //GetAccessTokenResponse result = null;
            try {
                GetAccessTokenResponse result = client.getAccessToken(getAccessTokenRequest);
                //设置缓存和过期时间expireIn，因为每个应用的accessToken是彼此独立的，所以进行缓存时加上H5应用ID区分应用来进行存储。
                redisUtil.setEx("DingDingAccessToken"+AGENTID, result.getBody().accessToken, result.getBody().expireIn, TimeUnit.SECONDS);
                accessToken = result.getBody().accessToken;
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    logger.error("【钉钉】", "获取access_token失败，errCode：{"+err.code+"}，errMsg：", err.message);
                }
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    logger.error("【钉钉】", "获取access_token失败，errCode：{"+err.code+"}，errMsg：", err.message);
                }
                logger.error(_err.getMessage(),_err);
            }
        }
        return accessToken;
    }


    /**
     * 根据手机号刷新用户钉钉id
     */
    @PostMapping("/getDingDingUserIdByPhone")
    @ResponseBody
    public JSONObject getDingDingUserIdByPhone(HttpServletRequest request, HttpServletResponse response, @org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            ObjectMapper objectMapper = new ObjectMapper();//参数格式转换
            Map<String, String> map = objectMapper.readValue(sentStr, HashMap.class);
            String telephone = map.get("telephone");//联系电话
            String userId = map.get("userId");//联系电话

            String accessToken = getAccessToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(telephone);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
            logger.info("【钉钉】，根据用户手机号获取钉钉用户id返回："+rsp.getBody());
            if(rsp.getErrcode()==0){
                String dingdingId = rsp.getResult().getUserid();
                hrMapper.updateUserDingIdByUserId(userId,dingdingId);//.updateUserDingDingIdByUserId(userId,dingdingId);
                result.put("code", 1);
                result.put("dingdingId", dingdingId);
            }else{
                logger.error("【钉钉】", "根据用户手机号获取钉钉用户id失败，errCode：{"+rsp.getErrcode()+"}，errMsg：", rsp.getErrmsg());
                result.put("code", 0);
            }
        }catch (Exception e){
            logger.error("【钉钉】，根据用户手机号获取钉钉用户id失败：",e.getMessage(),e);
            result.put("code", 0);
        }
        return result;

    }




    /**
     * 获取考勤报表数据
     */
    @PostMapping("/getcolumnvalByDingDing")
    @ResponseBody
    public JSONObject getcolumnvalByDingDing(HttpServletRequest request, HttpServletResponse response, @org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            //获取accessToken
            String accessToken = getAccessToken();
            //获取考勤报表列定义
            List<OapiAttendanceGetattcolumnsResponse.ColumnForTopVo> attcolumnsList = getattcolumnsByDingDing(accessToken);
            //获取钉钉设置的考勤类型
            String[] aliasArr = setAliasList();
            String idListStr = "";
            Map<String,Object> aliasItem = new HashMap<>();
            for(String type:aliasArr){
                for(OapiAttendanceGetattcolumnsResponse.ColumnForTopVo item:attcolumnsList){
                    if(item.getAlias().equals(type)){
                        if("".equals(idListStr)){
                            idListStr = item.getId()+"";
                        }else {
                            idListStr = idListStr + "," + item.getId();
                        }
                        aliasItem.put(item.getAlias(),item.getId());
                    }
                }
            }
            //获取日期信息
            ObjectMapper objectMapper = new ObjectMapper();//参数格式转换
            Map<String, String> map = objectMapper.readValue(sentStr, HashMap.class);
            String countMonth = map.get("countMonth");//要统计的月份
            int LastDayByMonth = DateUtil.getMonthLastDay(countMonth);//获取该月的最后一天日期

            //参数设置
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
            OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
            req.setColumnIdList(idListStr);
            String startTime = countMonth+"-01 00:00:00";
            String endTime = countMonth+"-"+LastDayByMonth+" 23:59:59";
            req.setFromDate(StringUtils.parseDateTime(startTime));
            req.setToDate(StringUtils.parseDateTime(endTime));

            List<Map<String,Object>> userList = new TbUserJobLevelManage()
                    .addField("U.DingDingId AS dingDingId")
                    .addLeftJoin("THR_UserArchives U ON U.UserId = A.UserId")
                    .where("U.DingDingId IS NOT NULL")
                    .queryMap();
            if(userList!=null && userList.size()>0){
                for( Map<String,Object> userItem : userList ){
                    //获取用户钉钉id信息
                    req.setUserid(userItem.get("dingDingId").toString());
                    OapiAttendanceGetcolumnvalResponse rsp = client.execute(req, accessToken);
                    logger.info("【钉钉】，用户："+userItem.get("userId")+"获取考勤报表数据返回信息：\n"+rsp.getBody());

                    if(rsp.getErrcode()==0){
                        BigDecimal workHour = BigDecimal.ZERO;
                        BigDecimal attendanceDay = BigDecimal.ZERO;
                        BigDecimal businessTripsDay = BigDecimal.ZERO;
                        BigDecimal restDay = BigDecimal.ZERO;
                        BigDecimal noWorkHour = BigDecimal.ZERO;
                        BigDecimal lateTimes = BigDecimal.ZERO;
                        BigDecimal noSignIn = BigDecimal.ZERO;
                        BigDecimal yearHolidayHour = BigDecimal.ZERO;
                        BigDecimal childbirthHolidayHour = BigDecimal.ZERO;
                        BigDecimal companionChildbirthHour = BigDecimal.ZERO;
                        BigDecimal marryHolidayHour = BigDecimal.ZERO;
                        BigDecimal deathHolidayHour = BigDecimal.ZERO;
                        BigDecimal illHolidayHour = BigDecimal.ZERO;
                        BigDecimal thingHolidayHourByPublic = BigDecimal.ZERO;
                        BigDecimal thingHolidayHourByOther = BigDecimal.ZERO;
                        logger.info("aliasItem："+aliasItem);
                        //获取并计算各个参数值
                        List<OapiAttendanceGetcolumnvalResponse.ColumnValForTopVo> allList = rsp.getResult().getColumnVals();
                        for(OapiAttendanceGetcolumnvalResponse.ColumnValForTopVo columnValForTopVo:allList){
                            //工作时长(小时)
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("attendance_work_time").toString())){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    workHour = workHour.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                                //获取到的是分钟
                                if(workHour.compareTo(BigDecimal.ZERO)!=0){
                                    workHour = workHour.divide(new BigDecimal(60),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入
                                }
                            }
                            //出勤天数
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("attendance_days").toString())){
                            //if(columnValForTopVo.getColumnVo().getId()==aliasItem.get("attendance_days")){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    attendanceDay = attendanceDay.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                            }
                            ///出差时长(天数？)
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("business_trip_time").toString())){
                            //if(columnValForTopVo.getColumnVo().getId()==aliasItem.get("business_trip_time")){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    businessTripsDay = businessTripsDay.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                                //获取到的是分钟
                                if(businessTripsDay.compareTo(BigDecimal.ZERO)!=0){
                                    businessTripsDay = businessTripsDay.divide(new BigDecimal(60),2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入
                                }
                                /*
                                if(businessTripsDay.compareTo(BigDecimal.ZERO)!=0){
                                    businessTripsDay = businessTripsDay.divide(oneDayWorkHour,2,BigDecimal.ROUND_HALF_UP);//保留2位小数，四舍五入
                                }
                                 */
                            }
                            //休息天数
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("attendance_rest_days").toString())){
                            //if(columnValForTopVo.getColumnVo().getId()==aliasItem.get("attendance_rest_days")){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    restDay = restDay.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                            }
                            //旷工天数（小时？）
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("absenteeism_days").toString())){
                            //if(columnValForTopVo.getColumnVo().getId()==aliasItem.get("absenteeism_days")){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    noWorkHour = noWorkHour.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                                if(noWorkHour.compareTo(BigDecimal.ZERO)!=0){
                                    noWorkHour = noWorkHour.multiply(oneDayWorkHour);
                                }
                            }
                            //迟到（次）
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("late_times").toString())){
                            //if(columnValForTopVo.getColumnVo().getId()==aliasItem.get("late_times")){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    lateTimes = lateTimes.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                            }
                            //漏打卡（次）=上班缺卡次数+下班缺卡次数+补卡次数
                            //下班缺卡次数
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("off_work_lack_card_times").toString())){
                            //if(columnValForTopVo.getColumnVo().getId()==aliasItem.get("off_work_lack_card_times")){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    noSignIn = noSignIn.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                            }
                            //上班缺卡次数
                            if(columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("on_work_lack_card_times").toString())){
                            //if(columnValForTopVo.getColumnVo().getId()==aliasItem.get("on_work_lack_card_times")){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    noSignIn = noSignIn.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                            }
                            //补卡次数
                            if(aliasItem.get("making_up_lack_times")!=null && columnValForTopVo.getColumnVo().getId().toString().equals(aliasItem.get("making_up_lack_times").toString())){
                                List<OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnVals();
                                for(OapiAttendanceGetcolumnvalResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                    noSignIn = noSignIn.add(new BigDecimal(columnDayAndVal.getValue()));
                                }
                            }
                        }
                        //获取假期统计数据
                        //年假（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> yearHolidayHourList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"年假",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:yearHolidayHourList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                yearHolidayHour = yearHolidayHour.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            if(yearHolidayHour.compareTo(BigDecimal.ZERO)!=0){
                                yearHolidayHour = yearHolidayHour.multiply(oneDayWorkHour);
                            }
                        }
                        //产假（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> childbirthHolidayHourList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"产假",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:childbirthHolidayHourList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                childbirthHolidayHour = childbirthHolidayHour.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            if(childbirthHolidayHour.compareTo(BigDecimal.ZERO)!=0){
                                childbirthHolidayHour = childbirthHolidayHour.multiply(oneDayWorkHour);
                            }
                        }
                        //陪产假（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> companionChildbirthHourList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"陪产假",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:companionChildbirthHourList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                companionChildbirthHour = companionChildbirthHour.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            if(companionChildbirthHour.compareTo(BigDecimal.ZERO)!=0){
                                companionChildbirthHour = companionChildbirthHour.multiply(oneDayWorkHour);
                            }
                        }
                        //婚假（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> marryHolidayHourList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"婚假",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:marryHolidayHourList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                marryHolidayHour = marryHolidayHour.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            if(marryHolidayHour.compareTo(BigDecimal.ZERO)!=0){
                                marryHolidayHour = marryHolidayHour.multiply(oneDayWorkHour);
                            }
                        }
                        //丧假（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> deathHolidayHourList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"丧假",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:deathHolidayHourList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                deathHolidayHour = deathHolidayHour.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            if(deathHolidayHour.compareTo(BigDecimal.ZERO)!=0){
                                deathHolidayHour = deathHolidayHour.multiply(oneDayWorkHour);
                            }
                        }
                        //病假（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> illHolidayHourList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"病假",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:illHolidayHourList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                illHolidayHour = illHolidayHour.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            /*
                            if(illHolidayHour.compareTo(BigDecimal.ZERO)!=0){
                                illHolidayHour = illHolidayHour.multiply(oneDayWorkHour);
                            }
                             */
                        }
                        //事假-因公外出（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> thingHolidayHourByPublicList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"因公外出",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:thingHolidayHourByPublicList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                thingHolidayHourByPublic = thingHolidayHourByPublic.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            /*
                            if(thingHolidayHourByPublic.compareTo(BigDecimal.ZERO)!=0){
                                thingHolidayHourByPublic = thingHolidayHourByPublic.multiply(oneDayWorkHour);
                            }
                             */
                        }
                        //事假-其他（小时）
                        List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> thingHolidayHourByOtherList = getleavetimebynamesByDingDing(accessToken,userItem.get("dingDingId").toString(),"事假",startTime,endTime);
                        for(OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo columnValForTopVo:thingHolidayHourByOtherList){
                            List<OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal> columnVals = columnValForTopVo.getColumnvals();
                            for(OapiAttendanceGetleavetimebynamesResponse.ColumnDayAndVal columnDayAndVal : columnVals){
                                thingHolidayHourByOther = thingHolidayHourByOther.add(new BigDecimal(columnDayAndVal.getValue()));
                            }
                            /*
                            if(thingHolidayHourByOther.compareTo(BigDecimal.ZERO)!=0){
                                thingHolidayHourByOther = thingHolidayHourByOther.multiply(oneDayWorkHour);
                            }
                             */
                        }

                        TbUserAttendance tbUserAttendance = new TbUserAttendance();
                        tbUserAttendance.setUserId(userItem.get("userId").toString());//用户工号
                        tbUserAttendance.setAttendanceMonth(countMonth);//记录月份
                        tbUserAttendance.setWorkHour(workHour);//工作时长(小时)
                        tbUserAttendance.setAttendanceDay(attendanceDay);//出勤天数
                        tbUserAttendance.setBusinessTripsDay(businessTripsDay);//出差天数
                        tbUserAttendance.setRestDay(restDay);//休息天数
                        tbUserAttendance.setNoWorkHour(noWorkHour);//旷工(小时)
                        tbUserAttendance.setLateTimes(lateTimes);//迟到（次）
                        tbUserAttendance.setNoSignIn(noSignIn);//漏打卡（次）
                        tbUserAttendance.setYearHolidayHour(yearHolidayHour);//年假（小时）
                        tbUserAttendance.setChildbirthHolidayHour(childbirthHolidayHour);//产假（小时）
                        tbUserAttendance.setCompanionChildbirthHour(companionChildbirthHour);//陪产假（小时）
                        tbUserAttendance.setMarryHolidayHour(marryHolidayHour);//婚假（小时）
                        tbUserAttendance.setDeathHolidayHour(deathHolidayHour);//丧假（小时）
                        tbUserAttendance.setIllHolidayHour(illHolidayHour);//病假（小时）
                        tbUserAttendance.setThingHolidayHourByPublic(thingHolidayHourByPublic);//事假-因公外出（小时）
                        tbUserAttendance.setThingHolidayHourByOther(thingHolidayHourByOther);//事假-其他（小时）

                        tbUserAttendanceService.save(tbUserAttendance);


                    }
                }
            }
        } catch (Exception e) {
            logger.error("!!!!!获取获取考勤报表数据失败(getcolumnvalByDingDing)：", e.getMessage(),e);
        }
        result.put("code", 1);
        return result;

    }

    /**
     * 获取报表假期数据
     */
    public List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> getleavetimebynamesByDingDing(String accessToken,String userId,String leave_names,String startTime,String endTime){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getleavetimebynames");
            OapiAttendanceGetleavetimebynamesRequest req = new OapiAttendanceGetleavetimebynamesRequest();
            req.setUserid(userId);
            req.setLeaveNames(leave_names);
            req.setFromDate(StringUtils.parseDateTime(startTime));
            req.setToDate(StringUtils.parseDateTime(endTime));
            OapiAttendanceGetleavetimebynamesResponse rsp = client.execute(req, accessToken);
            logger.info("【钉钉】，用户："+userId+"获取考勤报表假期数据返回信息：\n"+rsp.getBody());
            List<OapiAttendanceGetleavetimebynamesResponse.ColumnValForTopVo> columns = rsp.getResult().getColumns();
            return columns;
        } catch (Exception e) {
            logger.error("!!!!!获取钉钉获取假期数据失败(getleavetimebynamesByDingDing)：", e.getMessage(),e);
            return null;
        }

    }



    /**
     * 获取钉钉设置的考勤类型
     */
    public String[] setAliasList(){
        String[] aliasArr = new String[]{
                "attendance_work_time",//工作时长
                "attendance_days",//出勤天数
                "business_trip_time",//出差时长(天数？)
                "attendance_rest_days",//休息天数
                "absenteeism_days",//旷工天数（小时？）
                "late_times",//迟到次数
                //漏打卡次数 = 下班缺卡次数 + 上班缺卡次数
                "off_work_lack_card_times",//下班缺卡次数
                "on_work_lack_card_times",//上班缺卡次数
                //"",//年假（小时）
                //"",//产假（小时）
                //"",//陪产假（小时）
                //"",//婚假（小时）
                //"",//丧假（小时）
                //"",//病假（小时）
                //"",//事假-因公外出（小时）
                //"",//事假-其他（小时）
        };
        return aliasArr;
    }

    /**
     * 获取考勤报表列定义
     */
    public List<OapiAttendanceGetattcolumnsResponse.ColumnForTopVo> getattcolumnsByDingDing(String accessToken){
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getattcolumns");
            OapiAttendanceGetattcolumnsRequest req = new OapiAttendanceGetattcolumnsRequest();
            OapiAttendanceGetattcolumnsResponse rsp = client.execute(req, accessToken);
            return rsp.getResult().getColumns();
        } catch (Exception e) {
            logger.error("!!!!!获取钉钉获取考勤报表列定义失败(getattcolumnsByDingDing)：", e.getMessage(),e);
            return null;
        }

    }


    /**
     * 获取考勤报表列定义
     */
    @PostMapping("/getattcolumnsByDingDing")
    @ResponseBody
    public R getattcolumnsByDingDing(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取accessToken
            String accessToken = getAccessToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getattcolumns");
            OapiAttendanceGetattcolumnsRequest req = new OapiAttendanceGetattcolumnsRequest();
            OapiAttendanceGetattcolumnsResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());
            //返回示例：
            //{"errcode":0,"errmsg":"ok","result":{"columns":[{"alias":"","expression_id":871443405,"extension":"{\"expressionType\":0,\"hasChangeExpression\":false,\"hasChangeMemo\":false,\"hasChangeOwner\":false,\"opType\":\"ADD\",\"opUserId\":\"223555656126435439\"}","id":871450405,"name":"专业版本测试","status":0,"sub_type":0,"type":1},{"alias":"1_off_duty_user_check_result","expression_id":138623202,"extension":"null","id":138628202,"name":"下班1打卡结果","status":0,"sub_type":0,"type":0},{"alias":"1_off_duty_user_check_time","expression_id":138623201,"extension":"null","id":138628201,"name":"下班1打卡时间","status":0,"sub_type":0,"type":0},{"alias":"1_on_duty_user_check_result","expression_id":138623200,"extension":"null","id":138628200,"name":"上班1打卡结果","status":0,"sub_type":0,"type":0},{"alias":"1_on_duty_user_check_time","expression_id":138623199,"extension":"null","id":138628199,"name":"上班1打卡时间","status":0,"sub_type":0,"type":0},{"alias":"2_off_duty_user_check_result","expression_id":138623206,"extension":"null","id":138628206,"name":"下班2打卡结果","status":0,"sub_type":0,"type":0},{"alias":"2_off_duty_user_check_time","expression_id":138623205,"extension":"null","id":138628205,"name":"下班2打卡时间","status":0,"sub_type":0,"type":0},{"alias":"2_on_duty_user_check_result","expression_id":138623204,"extension":"null","id":138628204,"name":"上班2打卡结果","status":0,"sub_type":0,"type":0},{"alias":"2_on_duty_user_check_time","expression_id":138623203,"extension":"null","id":138628203,"name":"上班2打卡时间","status":0,"sub_type":0,"type":0},{"alias":"3_off_duty_user_check_result","expression_id":138623210,"extension":"null","id":138628210,"name":"下班3打卡结果","status":0,"sub_type":0,"type":0},{"alias":"3_off_duty_user_check_time","expression_id":138623209,"extension":"null","id":138628209,"name":"下班3打卡时间","status":0,"sub_type":0,"type":0},{"alias":"3_on_duty_user_check_result","expression_id":138623208,"extension":"null","id":138628208,"name":"上班3打卡结果","status":0,"sub_type":0,"type":0},{"alias":"3_on_duty_user_check_time","expression_id":138623207,"extension":"null","id":138628207,"name":"上班3打卡时间","status":0,"sub_type":0,"type":0},{"alias":"absenteeism_days","expression_id":138623189,"extension":"null","id":138628189,"name":"旷工天数","status":0,"sub_type":0,"type":0},{"alias":"absenteeism_late_times","expression_id":138623184,"extension":"null","id":138628184,"name":"旷工迟到次数","status":0,"sub_type":0,"type":0},{"alias":"absenteeism_late_times","expression_id":138623212,"extension":"null","id":138628212,"name":"旷工迟到天数","status":0,"sub_type":0,"type":0},{"alias":"attendance_approve","expression_id":138623211,"extension":"null","id":138628211,"name":"关联的审批单","status":0,"sub_type":0,"type":0},{"alias":"attendance_class","expression_id":138623176,"extension":"null","id":138628176,"name":"出勤班次","status":0,"sub_type":2,"type":0},{"alias":"attendance_days","expression_id":138623177,"extension":"null","id":138628177,"name":"出勤天数","status":0,"sub_type":0,"type":0},{"alias":"attendance_rest_days","expression_id":138623178,"extension":"null","id":138628178,"name":"休息天数","status":0,"sub_type":0,"type":0},{"alias":"attendance_work_time","expression_id":138623179,"extension":"null","id":138628179,"name":"工作时长","status":0,"sub_type":0,"type":0},{"alias":"attend_result","expression_id":138623197,"extension":"null","id":138628197,"name":"考勤结果","status":0,"sub_type":1,"type":0},{"alias":"business_trip_time","expression_id":138623190,"extension":"null","id":138628190,"name":"出差时长","status":0,"sub_type":0,"type":0},{"alias":"late_minute","expression_id":138623181,"extension":"null","id":138628181,"name":"迟到时长","status":0,"sub_type":0,"type":0},{"alias":"late_times","expression_id":138623180,"extension":"null","id":138628180,"name":"迟到次数","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"事假","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"病假","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"年假","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"产假","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"陪产假","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"婚假","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"丧假","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"因公外出","status":0,"sub_type":0,"type":0},{"alias":"leave_","name":"产检假","status":0,"sub_type":0,"type":0},{"alias":"leave_early_minute","expression_id":138623186,"extension":"null","id":138628186,"name":"早退时长","status":0,"sub_type":0,"type":0},{"alias":"leave_early_times","expression_id":138623185,"extension":"null","id":138628185,"name":"早退次数","status":0,"sub_type":0,"type":0},{"alias":"making_up_lack_times","expression_id":138623175,"extension":"null","id":138628175,"name":"补卡次数","status":0,"sub_type":0,"type":0},{"alias":"off_work_lack_card_times","expression_id":138623188,"extension":"null","id":138628188,"name":"下班缺卡次数","status":0,"sub_type":0,"type":0},{"alias":"on_work_lack_card_times","expression_id":138623187,"extension":"null","id":138628187,"name":"上班缺卡次数","status":0,"sub_type":0,"type":0},{"alias":"out_time","expression_id":138623191,"extension":"null","id":138628191,"name":"外出时长","status":0,"sub_type":0,"type":0},{"alias":"overtime_approve_count","expression_id":138623193,"extension":"null","id":138628193,"name":"加班-审批单统计","status":0,"sub_type":0,"type":0},{"alias":"overtime_休息日加班","expression_id":138623195,"extension":"null","id":138628195,"name":"休息日加班","status":0,"sub_type":0,"type":0},{"alias":"overtime_工作日加班","expression_id":138623194,"extension":"null","id":138628194,"name":"工作日加班","status":0,"sub_type":0,"type":0},{"alias":"overtime_节假日加班","expression_id":138623196,"extension":"null","id":138628196,"name":"节假日加班","status":0,"sub_type":0,"type":0},{"alias":"plan_detail","expression_id":138623198,"extension":"null","id":138628198,"name":"班次","status":0,"sub_type":0,"type":0},{"alias":"serious_late_minute","expression_id":138623183,"extension":"null","id":138628183,"name":"严重迟到时长","status":0,"sub_type":0,"type":0},{"alias":"serious_late_times","expression_id":138623182,"extension":"null","id":138628182,"name":"严重迟到次数","status":0,"sub_type":0,"type":0},{"alias":"should_attendance_days","expression_id":138623174,"extension":"null","id":138628174,"name":"应出勤天数","status":0,"sub_type":0,"type":0}]},"request_id":"16ks3d99jefp1"}
            rsp.getResult().getColumns();
        } catch (Exception e) {
            logger.error("!!!!!获取钉钉获取考勤报表列定义失败(getattcolumnsByDingDing)：", e.getMessage(),e);
        }
        return R.ok();

    }

    /**
     * 推送工作通知
     */
    @PostMapping("/sendDingDingNotice")
    @ResponseBody
    public R sendDingDingNotice(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取accessToken
            String accessToken = getAccessToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(Long.parseLong(AGENTID));
            req.setUseridList("123905471526640640");
            OapiMessageCorpconversationAsyncsendV2Request.Msg obj1 = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            obj1.setMsgtype("text");
            OapiMessageCorpconversationAsyncsendV2Request.Text obj2 = new OapiMessageCorpconversationAsyncsendV2Request.Text();
            obj2.setContent("测试一下哟哟哟哟哟哟");
            obj1.setText(obj2);
            req.setMsg(obj1);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());

        } catch (Exception e) {
            logger.error("!!!!!推送钉钉通知信息失败(sendDingDingNotice)：", e.getMessage(),e);
        }

        return R.ok();

    }






}
